package com.zh.kotlin_mvvm

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import androidx.core.view.marginEnd
import androidx.core.view.marginStart
import com.blankj.utilcode.util.ScreenUtils
import com.zh.common.ktx.dp2px

/**
 * 动态到达固定位置
 */
class LineView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private var mWidth = 0
    private var mHeight = 0
    private val paint = Paint()
    private var valw = 0f
    private var valueAnimator: ValueAnimator? = null

    init {
        paint.color = Color.RED
        paint.style = Paint.Style.FILL_AND_STROKE
        paint.isAntiAlias = true
        paint.strokeWidth = 10f.dp2px.toFloat()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        if (MeasureSpec.AT_MOST == MeasureSpec.getMode(widthMeasureSpec)) {
            mWidth =
                ScreenUtils.getScreenWidth() - marginStart - marginEnd - paddingStart - paddingEnd
        }
        if (MeasureSpec.AT_MOST == MeasureSpec.getMode(heightMeasureSpec)) {
            mHeight = 5f.dp2px
        }
        if (MeasureSpec.EXACTLY == MeasureSpec.getMode(widthMeasureSpec)) {
            mWidth =
                MeasureSpec.getSize(widthMeasureSpec) - marginStart - marginEnd - paddingStart - paddingEnd
        }
        if (MeasureSpec.EXACTLY == MeasureSpec.getMode(heightMeasureSpec)) {
            mHeight = MeasureSpec.getSize(heightMeasureSpec)
        }
        setMeasuredDimension(mWidth, mHeight)
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        paint.color = Color.RED
        canvas?.drawLine(0f, 0f, mWidth.toFloat(), mHeight.toFloat(), paint)

        paint.color = Color.YELLOW
        canvas?.drawLine(0f, 0f, valw, mHeight.toFloat(), paint)
    }

    /**
     * 设置固定进度
     */
    fun setCurrent(vale: Float) {
        if (valueAnimator != null) {
            valueAnimator?.cancel()
        } else {
            valueAnimator = ValueAnimator.ofFloat(mWidth / 100f * vale)
        }
        valueAnimator?.let {
            it.duration = 2000
            it.addUpdateListener { anim ->
                valw = anim.animatedValue as Float
                postInvalidate()
            }
            it.start()
        }
    }
}
